package com.self.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.self.gateway.constant.GatewayConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Set;

/**
 * @version v1.0
 * @ClassName: TokenCheckFilter
 * @Description:
 * @Author: Mac
 * @Date: 2022/5/28 11:54
 */
@Component
public class TokenCheckFilter implements GlobalFilter, Ordered {


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${access.allow.uris:/admin/login,/user/gt/register,/user/login,/user/users/register,/user/sms/sendTo}")
    private Set<String> allowAccessUri;
    
    /**
     * @Title: 校验token
     * @Description: 
     * @Param [exchange, chain]
     * @Return reactor.core.publisher.Mono<java.lang.Void>
     * @Author Mac
     * @Throws
     * @Date 2022/5/28 11:56
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //不需要token能访问的
        if (noTokenAccess(exchange)){
            return chain.filter(exchange);
        }
         //获取token
        String token = getToken(exchange);
        //判断token是否有效
        if (StringUtils.isBlank(token)){
            return buildNoAuthorizationResult(exchange);
        }
        Boolean hasKey = redisTemplate.hasKey(GatewayConstant.JWT_TOKEN_PROFIX+token.hashCode());
        if (hasKey != null && hasKey){
            return chain.filter(exchange);
        }
       return buildNoAuthorizationResult(exchange);
    }

    private Mono<Void> buildNoAuthorizationResult(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = response.getHeaders();
        headers.set(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON_VALUE);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("errorCode",HttpStatus.UNAUTHORIZED.value());
        jsonObject.put("errorMsg","Token is null or error");
        DataBuffer wrap = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Flux.just(wrap));
    }

    private String getToken(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        String first = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        return StringUtils.isBlank(first)?null:first.replace("bearer ","");
    }

    private boolean noTokenAccess(ServerWebExchange exchange) {
        if (CollectionUtils.isEmpty(allowAccessUri)){
            return false;
        }
        String path = exchange.getRequest().getURI().getPath();
        if (allowAccessUri.contains(path)){
            return true;
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
